//
//  HSAddQRViewController.m
//  hsdyOrderSystem
//
//  Created by XunFengKJ on 2017/11/9.
//  Copyright © 2017年 赖国锋. All rights reserved.
//

#import "HSAddQRViewController.h"
#import "HSTableDetailVC.h"
#import "HSTableManagedCell.h"
#import "HSQRCodeModel.h"
#import <Photos/PHPhotoLibrary.h>
#import <Photos/PHAssetChangeRequest.h>

static NSString * cellindentifier = @"tableManagedCell";
@interface HSAddQRViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITextField *tableCountTX;
@property (strong, nonatomic) UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIButton *creatQRBtn;

@property (strong, nonatomic) NSMutableArray *dataArr;//数据
@end

@implementation HSAddQRViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"桌位管理";
    self.view.backgroundColor = LCOLOROFBACK;
    self.creatQRBtn.layer.cornerRadius = 15;
    self.creatQRBtn.layer.masksToBounds = YES;
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:[NSString stringWithFormat:@"%@",[HSTableManagedCell class]] bundle:nil ] forCellReuseIdentifier:cellindentifier];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = XFUIColorFromRGB(0xf0f2f5);
    [self.view addSubview:self.tableView];
    WEAKSELF
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.top.equalTo(weakSelf.view).offset(80);
        make.bottom.equalTo(weakSelf.view);
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HSTableManagedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellindentifier];
    cell.model = self.dataArr[indexPath.row];
    cell.selectionStyle = 0;
    cell.saveBtnClickBlock = ^(NSInteger btnTag) {
        HSTableManagedCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [self loadImageToPhotoAlbumFinished:cell.QRCodeImageV.image];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma MARK - 写入图片到相册
- (void)loadImageToPhotoAlbumFinished:(UIImage *)image{
    [self showLoadingWithClear:YES];
    WEAKSELF
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
//        LGFLog(@"success =%zd - error=%@",success,error);
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
             [weakSelf hideLoading];
            if (success == 1) {
                 [SOAutoHideMessageView showMessage:@"保存到相册成功" inView:nil hideDelay:1.5];
            }else{
                [SOAutoHideMessageView showMessage:@"保存失败，请重新操作" inView:nil hideDelay:1.5];
            }
        });
    }];
}

#pragma MARK - 生成二维码
- (IBAction)creatQR:(id)sender {
    if (self.tableCountTX.text.length ==0) {
        [SOAutoHideMessageView showMessage:@"请先输入桌位数量" inView:nil];
        return;
    }
    [self.tableCountTX resignFirstResponder];
    //增加二维码
    [self postRequestQRCodeWithTableCount:self.tableCountTX.text];
}

//增加二维码
-(void)postRequestQRCodeWithTableCount:(NSString *)tableCount{
    WEAKSELF
    [self showLoadingWithClear:YES];
    [XFPostRequest postAddQRCodeShopId:[BookShareUserInforDefault readUserUid] tables:tableCount action:@"1" success:^(id responseObject) {
        if ([[responseObject safeJsonObjectForKey:@"status"] integerValue] == 200) {
//            LGFLog(@"===%@",responseObject);
            [weakSelf postLookQRCode];
        }
    } failure:^(NSError *error) {
        [weakSelf hideLoading];
        [SOAutoHideMessageView showMessage:LNETWORKERROR inView:self.view];
    }];
}

//查看二维码
-(void)postLookQRCode{
    WEAKSELF
    [self showLoadingWithClear:YES];
    [XFPostRequest postLookQRCodeByShopId:[BookShareUserInforDefault readUserUid] success:^(id responseObject) {
        [weakSelf hideLoading];
        if ([[responseObject safeJsonObjectForKey:@"status"] integerValue] == 200) {
            LGFLog(@"===%@",responseObject);
            [weakSelf initTableView];
            weakSelf.dataArr  = [HSQRCodeModel mj_objectArrayWithKeyValuesArray:[responseObject safeJsonObjectForKey:@"content"] ];
        }else{
            [weakSelf.dataArr removeAllObjects];
            [SOAutoHideMessageView showMessage:[responseObject safeJsonObjectForKey:@"msg"] inView:weakSelf.view];
        }
        [weakSelf.tableView reloadData];
    } failure:^(NSError *error) {
        [weakSelf hideLoading];
        [SOAutoHideMessageView showMessage:LNETWORKERROR inView:self.view];
    }];
}

#pragma mark - lazy
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = @[].mutableCopy;
    }
    return _dataArr;
}

@end
